<template>
  <div class="admin-home">
    <!-- 顶部导航栏 -->
    <el-header class="header">
      <div class="header-left">
        <h2>管理员控制台</h2>
      </div>
      <div class="header-right">
        <el-dropdown @command="handleCommand">
          <el-button>
            <el-icon><User /></el-icon>
            {{ userInfo.username }}
            <el-icon><ArrowDown /></el-icon>
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="personalInfo">修改个人信息</el-dropdown-item>
              <el-dropdown-item command="logout">退出登录</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </el-header>

    <!-- 主要内容区域 -->
    <el-container class="main-container">
      <!-- 左侧菜单 -->
      <el-aside width="200px" class="aside">
        <el-menu
          :default-active="activeMenu"
          @select="handleMenuSelect"
        >
          <el-menu-item index="users">
            <el-icon><User /></el-icon>
            <span>用户管理</span>
          </el-menu-item>
          <el-menu-item index="products">
            <el-icon><Goods /></el-icon>
            <span>商品管理</span>
          </el-menu-item>
          <el-menu-item index="categories">
            <el-icon><Folder /></el-icon>
            <span>分类管理</span>
          </el-menu-item>
        </el-menu>
      </el-aside>

      <!-- 右侧内容 -->
      <el-main class="main">
        <!-- 用户未登录提示 -->
        <div v-if="!userInfo.id && !userLoading" class="login-tip">
          <el-empty description="请先登录后再查看订单">
            <el-button type="primary" @click="$router.push('/login')">
              去登录
            </el-button>
          </el-empty>
        </div>

        <!-- 用户管理 -->
        <div v-if="activeMenu === 'users'" class="content-section">
          <div class="section-header">
            <h3>用户管理</h3>
          </div>

          <el-table :data="users" style="width: 100%">
            <el-table-column prop="id" label="ID" width="80" />
            <el-table-column prop="username" label="用户名" />
            <el-table-column prop="userType" label="用户类型" width="100">
              <template #default="scope">
                <el-tag :type="getUserTypeType(scope.row.userType)">
                  {{ getUserTypeText(scope.row.userType) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="phone" label="电话" width="120" />
            <el-table-column prop="email" label="邮箱" width="180" />
            <el-table-column prop="createTime" label="注册时间" width="180">
              <template #default="scope">
                {{ formatDate(scope.row.createTime) }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="150">
              <template #default="scope">
                <el-button
                  size="small"
                  type="danger"
                  @click="deleteUser(scope.row.id)"
                  :disabled="scope.row.userType === 'admin'"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <!-- 商品管理 -->
        <div v-if="activeMenu === 'products'" class="content-section">
          <div class="section-header">
            <h3>商品管理</h3>
          </div>

          <el-table :data="products" style="width: 100%">
            <el-table-column prop="id" label="ID" width="80" />
            <el-table-column prop="name" label="商品名称" />
            <el-table-column prop="price" label="价格" width="100">
              <template #default="scope">
                ¥{{ scope.row.price }}
              </template>
            </el-table-column>
            <el-table-column prop="stock" label="库存" width="100" />
            <el-table-column prop="sales" label="销量" width="100" />
            <el-table-column prop="categoryName" label="分类" width="120" />
            <el-table-column prop="sellerName" label="卖家" width="120" />
            <el-table-column label="操作" width="150">
              <template #default="scope">
                <el-button
                  size="small"
                  type="danger"
                  @click="deleteProduct(scope.row.id)"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <!-- 分类管理 -->
        <div v-if="activeMenu === 'categories'" class="content-section">
          <div class="section-header">
            <h3>分类管理</h3>
            <el-button type="primary" @click="showAddCategoryDialog = true">
              <el-icon><Plus /></el-icon>
              添加分类
            </el-button>
          </div>

          <el-table :data="categories" style="width: 100%">
            <el-table-column prop="id" label="ID" width="80" />
            <el-table-column prop="name" label="分类名称" />
            <el-table-column prop="level" label="层级" width="100">
              <template #default="scope">
                {{ scope.row.level }}级分类
              </template>
            </el-table-column>
            <el-table-column prop="parentName" label="父分类" width="120" />
            <el-table-column label="操作" width="200">
              <template #default="scope">
                <el-button size="small" @click="editCategory(scope.row)">
                  编辑
                </el-button>
                <el-button
                  size="small"
                  type="danger"
                  @click="deleteCategory(scope.row.id)"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-main>
    </el-container>

    <!-- 添加/编辑分类对话框 -->
    <el-dialog
      v-model="showAddCategoryDialog"
      :title="editingCategory ? '编辑分类' : '添加分类'"
      width="500px"
    >
      <el-form
        ref="categoryFormRef"
        :model="categoryForm"
        :rules="categoryRules"
        label-width="100px"
      >
        <el-form-item label="分类名称" prop="name">
          <el-input v-model="categoryForm.name" />
        </el-form-item>
        <el-form-item label="分类层级" prop="level">
          <el-select v-model="categoryForm.level" style="width: 100%">
            <el-option label="一级分类" :value="1" />
            <el-option label="二级分类" :value="2" />
            <el-option label="三级分类" :value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label="父分类" prop="parentId">
          <el-select
            v-model="categoryForm.parentId"
            style="width: 100%"
            :disabled="categoryForm.level === 1"
          >
            <el-option label="无" :value="0" />
            <el-option
              v-for="category in parentCategories"
              :key="category.id"
              :label="category.name"
              :value="category.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showAddCategoryDialog = false">取消</el-button>
        <el-button type="primary" @click="saveCategory">保存</el-button>
      </template>
    </el-dialog>

    <!-- 修改个人信息对话框 -->
    <el-dialog v-model="showPersonalInfoDialog" title="修改个人信息" width="400px">
      <el-form :model="personalInfoForm" :rules="personalInfoRules" ref="personalInfoFormRef" label-width="80px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="personalInfoForm.username" />
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="personalInfoForm.phone" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="personalInfoForm.email" />
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="personalInfoForm.address" type="textarea" :rows="2" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showPersonalInfoDialog = false">取消</el-button>
        <el-button type="primary" @click="submitPersonalInfo">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { User, ArrowDown, Goods, Folder, Plus } from '@element-plus/icons-vue'
import {
  getAllProducts,
  deleteProduct as deleteProductApi
} from '../api/product.js'
import {
  getAllCategories,
  addCategory,
  updateCategory,
  deleteCategory as deleteCategoryApi
} from '../api/category.js'
import { getUserInfo, updateUserInfo, getAllUsers, deleteUser as deleteUserApi } from '../api/user.js'

const router = useRouter()

// 响应式数据
const activeMenu = ref('users')
const users = ref([])
const products = ref([])
const categories = ref([])
const showAddCategoryDialog = ref(false)
const editingCategory = ref(null)
const userInfo = ref({ username: '管理员' })
const userLoading = ref(false)
const showPersonalInfoDialog = ref(false)
const personalInfoForm = reactive({ username: '', phone: '', email: '', address: '', deleted: 0 })
const personalInfoFormRef = ref()
const personalInfoRules = {
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  phone: [{ pattern: /^1[3-9]\d{9}$/, message: '请输入正确手机号', trigger: 'blur' }],
  email: [{ type: 'email', message: '请输入正确邮箱', trigger: 'blur' }],
  address: [{ required: true, message: '请输入地址', trigger: 'blur' }]
}

const categoryForm = reactive({
  name: '',
  level: 1,
  parentId: 0
})

const categoryRules = {
  name: [
    { required: true, message: '请输入分类名称', trigger: 'blur' }
  ],
  level: [
    { required: true, message: '请选择分类层级', trigger: 'change' }
  ]
}

// 计算属性
const parentCategories = computed(() => {
  return categories.value.filter(cat => cat.level < categoryForm.level)
})

// 方法
const loadUsers = async () => {
  try {
    const res = await getAllUsers()
    if (res && (res.state === 200 || res.code === 200)) {
      users.value = res.data || []
    } else {
      throw new Error(res?.message || '加载用户失败')
    }
  } catch (error) {
    console.error('加载用户失败:', error)
    
    if (error.response) {
      const status = error.response.status
      switch (status) {
        case 401:
          ElMessage.error('请先登录')
          router.push('/login')
          break
        case 403:
          ElMessage.error('权限不足，只有管理员可以查看用户列表')
          router.push('/login')
          break
        case 404:
          ElMessage.error('接口不存在，请检查后端服务是否启动')
          break
        default:
          ElMessage.error(`加载用户失败: ${error.message}`)
      }
    } else {
      ElMessage.error(error.message || '网络错误，请检查后端服务是否启动')
    }
  }
}

const loadProducts = async () => {
  try {
    const res = await getAllProducts()
    products.value = res.data || []
  } catch (error) {
    console.error('加载商品失败:', error)
    ElMessage.error('加载商品失败')
  }
}

const loadCategories = async () => {
  try {
    const res = await getAllCategories()
    categories.value = res.data || []
  } catch (error) {
    console.error('加载分类失败:', error)
  }
}

const loadUserInfo = async () => {
  try {
    userLoading.value = true
    const res = await getUserInfo()
    
    if (res && (res.state === 200 || res.code === 200)) {
      const userData = res.data
      
      Object.assign(personalInfoForm, {
        username: userData.username || '',
        phone: userData.phone || '',
        email: userData.email || '',
        address: userData.address || '',
        deleted: userData.deleted ?? 0
      })
      userInfo.value = userData || { username: '管理员' }
    } else {
      throw new Error(res?.message || '获取用户信息失败')
    }
  } catch (error) {
    console.error('获取用户信息失败:', error)
    throw error
  } finally {
    userLoading.value = false
  }
}

const handleMenuSelect = (index) => {
  activeMenu.value = index
  if (index === 'users') {
    loadUsers()
  } else if (index === 'products') {
    loadProducts()
  } else if (index === 'categories') {
    loadCategories()
  }
}

const editCategory = (category) => {
  editingCategory.value = category
  Object.assign(categoryForm, category)
  showAddCategoryDialog.value = true
}

const saveCategory = async () => {
  try {
    if (editingCategory.value) {
      await updateCategory(editingCategory.value.id, categoryForm)
      ElMessage.success('更新成功')
    } else {
      await addCategory(categoryForm)
      ElMessage.success('添加成功')
    }
    showAddCategoryDialog.value = false
    resetCategoryForm()
    loadCategories()
  } catch (error) {
    console.error('保存分类失败:', error)
    ElMessage.error('保存失败')
  }
}

const deleteCategory = async (id) => {
  try {
    await ElMessageBox.confirm('确认删除该分类？', '提示')
    await deleteCategoryApi(id)
    ElMessage.success('删除成功')
    loadCategories()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

const deleteProduct = async (id) => {
  try {
    await ElMessageBox.confirm('确认删除该商品？', '提示')
    await deleteProductApi(id)
    ElMessage.success('删除成功')
    loadProducts()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

const deleteUser = async (id) => {
  try {
    await ElMessageBox.confirm('确认删除该用户？此操作不可恢复！', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await deleteUserApi(id)
    ElMessage.success('删除成功')
    loadUsers()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error(error.message || '删除失败')
    }
  }
}

const resetCategoryForm = () => {
  editingCategory.value = null
  Object.assign(categoryForm, {
    name: '',
    level: 1,
    parentId: 0
  })
}

const submitPersonalInfo = () => {
  personalInfoFormRef.value.validate(async valid => {
    if (!valid) return
    try {
      // 数据验证
      const submitData = {
        username: personalInfoForm.username?.trim() || '',
        phone: personalInfoForm.phone?.trim() || '',
        email: personalInfoForm.email?.trim() || '',
        address: personalInfoForm.address?.trim() || ''
      }
      
      // 验证必填字段
      if (!submitData.username) {
        ElMessage.error('用户名不能为空')
        return
      }
      
      await updateUserInfo(submitData)
      ElMessage.success('修改成功')
      showPersonalInfoDialog.value = false
      loadUserInfo()
    } catch (error) {
      console.error('修改个人信息失败:', error)
      ElMessage.error('修改失败')
    }
  })
}

const handleCommand = (command) => {
  switch (command) {
    case 'personalInfo':
      showPersonalInfoDialog.value = true
      loadUserInfo()
      break
    case 'logout':
      router.push('/login')
      break
  }
}

const getUserTypeType = (userType) => {
  const typeMap = {
    buyer: 'success',
    seller: 'warning',
    admin: 'danger'
  }
  return typeMap[userType] || 'info'
}

const getUserTypeText = (userType) => {
  const textMap = {
    buyer: '买家',
    seller: '卖家',
    admin: '管理员'
  }
  return textMap[userType] || '未知'
}

const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN')
}

// 生命周期
onMounted(async () => {
  try {
    // 先加载用户信息
    await loadUserInfo()
    
    // 尝试加载用户列表，如果失败会显示相应的错误信息
    loadUsers()
  } catch (error) {
    console.error('初始化失败:', error)
    ElMessage.error('初始化失败，请重新登录')
    router.push('/login')
  }
})
</script>

<style scoped>
.admin-home {
  height: 100vh;
  display: flex;
  flex-direction: column;
}

.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  background: #fff;
  border-bottom: 1px solid #e4e7ed;
  padding: 0 20px;
}

.header-left h2 {
  margin: 0;
  color: #409eff;
}

.main-container {
  flex: 1;
  height: calc(100vh - 60px);
}

.aside {
  background: #fff;
  border-right: 1px solid #e4e7ed;
}

.main {
  padding: 20px;
  background: #f5f7fa;
}

.content-section {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.section-header h3 {
  margin: 0;
  color: #333;
}
</style> 